﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.ProBuilder.MeshOperations;


public class Grappling : MonoBehaviour
{
    [Header("references")]
    public PlayerMovement pm;
    public Transform cameraTransform;
    public Transform gunTip;
    public LayerMask whatIsGrappleable;
    public LineRenderer lr;
    [Header("Grappling")]
    public float maxGrappleDistance;
    public float grappleDelayTime;
    public float overshootYAxis;
    private Vector3 grapplePoint;

    [Header("Cooldown")]
    public float grapplingCd;
    private float grapplingCdTimer;

    public bool grappling;
    public bool grappleRequest;
    private void Start()
    {
        pm = GetComponent<PlayerMovement>();
        pm.OnGrapplAction += OnGrappleHandler;
    }

    private void OnGrappleHandler(bool obj)
    {
        grappleRequest = obj;
    }

    private void Update()
    {
        if(grappleRequest) StartGrapple();
        if(grapplingCdTimer >0)
        {
            grapplingCdTimer -= Time.deltaTime;
        }
    }

    private void LateUpdate()
    {
        if (grappling)
        {
            lr.SetPosition(0, gunTip.position);
        }
    }
    void CalculateGrappleDistancet()
    {

            
    }
    void StartGrapple()
    {
        if(grapplingCdTimer > 0)
        {
            return;
        }
        grappling = true;
        pm.freeze = true;
        RaycastHit hit;
        if (Physics.Raycast(cameraTransform.position, cameraTransform.forward, out hit, maxGrappleDistance, whatIsGrappleable))
        {
            grapplePoint = hit.point;
            Invoke(nameof(ExecuteGrapple), grappleDelayTime);
        }else
        {
            grapplePoint = cameraTransform.position + cameraTransform.forward * maxGrappleDistance;
            Invoke(nameof(StopGrapple), grappleDelayTime);
        }
        lr.enabled = true;
        lr.positionCount = 2;
        lr.SetPosition(1, grapplePoint);
    }
    void ExecuteGrapple()
    {
        pm.freeze = false;

        Vector3 lowestPoint = new Vector3(transform.position.x, transform.position.y - 1f, transform.position.z);
        float grapplePointRelativeYPos = grapplePoint.y - lowestPoint.y;
        float highestPointOnArc = grapplePointRelativeYPos + overshootYAxis;
        if (grapplePointRelativeYPos < 0)
        {
            highestPointOnArc = overshootYAxis;
        }
        Debug.Log("highestPointOnArc"+ highestPointOnArc);
        pm.JumpToPostiton(grapplePoint, highestPointOnArc);
        Invoke(nameof(StopGrapple), grappleDelayTime);
    }
    public void StopGrapple()
    {
        pm.freeze = false;
        grappling = false;
        grapplingCdTimer = grapplingCd;
        lr.enabled  = false;
    }
}
